import { getTestGetverificationcode } from "@/api/siderBar/test"
import { message } from "ant-design-vue";

interface Action {
    (mobile: string): Promise<unknown>
}
export function useVerifyCode(duration: number, mobile: MaybeRefOrGetter<string>, action: Action) {
    const lock = ref(false)
    const { remain, running, start, stop } = useCutdown(duration)
    async function triggerSend() {
        const target = toValue(mobile)
        if (!target) {
            message.error('请先输入手机号')
            return
        }
        if (toValue(lock)) return;
        try {
            lock.value = true
            await action(target)
            lock.value = false
            if (import.meta.env.DEV) {
                const { copy } = useCopy(void 0, { tip: false })
                const ret = await getTestGetverificationcode({ mobile: target })
                copy(ret.code)
                message.success('验证码已复制到剪贴板')
            } else {
                message.success('验证码发送成功')
            }
            start()
        } catch (error) {
            console.log("useVerifyCode", error)
            lock.value = false
            message.error('验证码发送失败')
            stop()
        }         
    }
    function reset() {
        lock.value = false
        stop()
    }
    return {
        remain,
        running,
        triggerSend,
        reset
    }
}